<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\BaseUser;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;
use app\common\model\BehaviorRecordDetail;
use app\common\model\BehaviorRecordImage;
use think\Db;
use think\Exception;

/**
 * 学生
 */
class Student extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['profile', 'lists', 'behaviorRecords'];

    protected $behaviorCategoryType = [BehaviorCategory::STUDENT];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (学生信息)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/17)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/profile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="学生ID", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1581909005",
    "data": {
    "id": 2369,
    "number": "20191008",
    "edu_id_number": "1008",
    "card_number": "55AA2254645644",
    "id_type": null,
    "id_number": null,
    "name": "薛凯琦",
    "pinyin": "wangxiaoer",
    "gender": 0,
    "birthday": "2005-03-12",
    "enrollment_type": "10015",
    "enrollment_year": "10015",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "status": 1,
    "created_at": 1574066510,
    "school_id": 3,
    "avatar": "https://mp.uxuj.cn/uploads/20191120/9100de52592d359342e1d4a4e117e7ad.jpg",
    "parents_id": 112,
    "nationality_id": null,
    "nation_id": null,
    "political_appearance_id": null,
    "address_id": null,
    "is_bed": 0,
    "class_name": "1班",
    "grade_name": "一年级",
    "headmaster_id": 42,
    "headmaster_name": null,
    "positive_score": 0,
    "negative_score": 0
    }
    })
     */
    public function profile()
    {
        $id = $this->request->request('id', 0);

        $result = \app\common\model\Student::alias('student')
            ->join('__CLASSES__ classes', 'classes.id = student.class_id')
            ->join('__GRADE__ grade', 'grade.id = student.grade_id')
            ->join('__SCHOOL__ school', 'school.id = student.school_id')
            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->where('student.id', $id)
            ->field('student.*,school.name school_name,classes.name class_name,grade.name grade_name,classes.headmaster headmaster_id,user.nickname headmaster_name')
            ->find();

        if ($result && !strstr($result->avatar, 'http') && strstr($result->avatar, '/uploads/')) {
            $result->avatar = config('mp.url') . $result->avatar;
        }

        $result->gender_text = BaseUser::getGender($result->gender);

        $records = BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where('record.student_id', '>', 0)
            ->where('detail.behavior_category_type', BehaviorCategory::STUDENT)
            ->where('record.student_id', $id)
            ->field('SUM(CASE WHEN detail.behavior_type = 1 THEN detail.score ELSE 0 END) positive_score,ABS(SUM(CASE WHEN detail.behavior_type = 2 THEN detail.score ELSE 0 END)) negative_score')
            ->order('score', 'desc')
            ->find();

        $result['positive_score'] = $records->positive_score ? $records->positive_score : 0;//积极分
        $result['negative_score'] = $records->negative_score ? $records->negative_score : 0;//消积分

        $this->success('', $result);
    }

    /**
     * @ApiTitle    (学生列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/18)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/lists)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiParams   (name="grade_id", type="int", required=true, description="年级 id", sample="")
     * @ApiParams   (name="class_id", type="int", required=false, description="班级 id", sample="")
     * @ApiParams   (name="keywords", type="int", required=false, description="搜索关键词", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1582011258",
    "data": {
    "total": 9,
    "per_page": 15,
    "current_page": 1,
    "last_page": 1,
    "data": [
    {
    "id": 2369,
    "number": "20191008",
    "card_number": "55AA2254645644",
    "name": "薛凯琦",
    "pinyin": "wangxiaoer",
    "gender": 0,
    "birthday": "2005-03-12",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574066510
    },
    {
    "id": 2370,
    "number": "20191007",
    "card_number": "55AA2243A976BE",
    "name": "李天熠",
    "pinyin": "wangxiaoyi",
    "gender": 1,
    "birthday": "2005-03-02",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574067649
    },
    {
    "id": 2371,
    "number": "20191006",
    "card_number": "55AA22465DB68F",
    "name": "刘蕊",
    "pinyin": "wangxiaomei",
    "gender": 0,
    "birthday": "2005-01-01",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574154272
    },
    {
    "id": 2372,
    "number": "20191001",
    "card_number": "55AA22454F163E",
    "name": "何东轩",
    "pinyin": "hedongxuan",
    "gender": 1,
    "birthday": "2005-02-02",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574217106
    },
    {
    "id": 2373,
    "number": "20191005",
    "card_number": "55AAB0F2AF0DE0",
    "name": "苏昭萍",
    "pinyin": "suzhaoping",
    "gender": 0,
    "birthday": "2005-01-01",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574217581
    },
    {
    "id": 2374,
    "number": "20191004",
    "card_number": "55AA22453BD68A",
    "name": "钱思妤",
    "pinyin": "qiansi",
    "gender": 0,
    "birthday": "2005-02-02",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574217651
    },
    {
    "id": 2375,
    "number": "20191003",
    "card_number": "55AA444DCDF632",
    "name": "张拯",
    "pinyin": "zhangzhengming",
    "gender": 1,
    "birthday": "2005-03-02",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574217741
    },
    {
    "id": 2376,
    "number": "20191002",
    "card_number": "55AAB0F6A89D73",
    "name": "袁欣",
    "pinyin": "yuanxinchen",
    "gender": 0,
    "birthday": "2005-03-02",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574217921
    },
    {
    "id": 2378,
    "number": "20191009",
    "card_number": "55AA2254645643",
    "name": "王小钰",
    "pinyin": "wangxiao",
    "gender": 1,
    "birthday": "1990-09-14",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 97,
    "created_at": 1574666753
    }
    ]
    }
    })
     */
    public function lists()
    {
        $school_id = $this->request->request('school_id', 0);
        $grade_id = $this->request->request('grade_id', 0);
        $class_id = $this->request->request('class_id', 0);
        $keywords = $this->request->request('keywords', '');
        $listRows = $this->request->request('listRows', 30);

        if ($class_id) {
            $list = \app\common\model\Student::alias('student')
                ->join('__CLASSES__ classes', 'classes.id = student.class_id')
                ->where('student.school_id', $school_id)
                ->where('student.class_id', $class_id)
                ->where('student.grade_id', $grade_id)
                ->where(function ($query) use ($keywords) {
                    if ($keywords) {
                        $query->where('student.name|student.number', 'like', "%$keywords%");
                    }
                })
                ->where('student.status', \app\common\model\Student::DISPLAY)
                ->field('student.id,student.number,student.card_number,student.name,student.avatar,student.pinyin,student.gender,student.birthday,student.school_id,student.grade_id,student.class_id,student.created_at,classes.name class_name')
                ->paginate($listRows);
        } else {
            $list = \app\common\model\Student::alias('student')
                ->join('__CLASSES__ classes', 'classes.id = student.class_id')
                ->where('student.school_id', $school_id)
                ->where('student.grade_id', $grade_id)
                ->where(function ($query) use ($keywords) {
                    if ($keywords) {
                        $query->where('student.name|student.number', 'like', "%$keywords%");
                    }
                })
                ->where('student.status', \app\common\model\Student::DISPLAY)
                ->field('student.id,student.number,student.card_number,student.name,student.avatar,student.pinyin,student.gender,student.birthday,student.school_id,student.grade_id,student.class_id,student.created_at,classes.name class_name')
                ->paginate($listRows);
        }

        if ($list) {
            $list = $list->toArray();

            foreach ($list['data'] as $key => $datum) {
                if (!strstr($datum['avatar'], 'http') && strstr($datum['avatar'], '/uploads/')) {
                    $list['data'][$key]['avatar'] = config('mp.url') . $datum['avatar'];
                }
            }
        }

        $this->success('', $list);

    }

    /**
     * @ApiTitle    (行为分类列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/18)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/behaviorCategory)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function behaviorCategory()
    {
        $data = BehaviorCategory::whereIn('type', $this->behaviorCategoryType)
            ->where('school_id', $this->auth->school_id)
            ->select();
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (行为列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/17)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/behaviors)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1579242668",
    "data": {
    "positive": [
    {
    "id": 5,
    "name": "学生测试1",
    "list": [
    {
    "id": 8,
    "name": "测试3",
    "category_id": 5,
    "type": 1,
    "score": 1,
    "image_id": 2,
    "category_name": "学生测试1",
    "image_url": "http://assess.uxuj.test/uploads/behavior/behavior02.png"
    },
    {
    "id": 9,
    "name": "测试2",
    "category_id": 5,
    "type": 1,
    "score": 1,
    "image_id": 0,
    "category_name": "学生测试1",
    "image_url": null
    },
    {
    "id": 10,
    "name": "测试1",
    "category_id": 5,
    "type": 1,
    "score": 2,
    "image_id": 0,
    "category_name": "学生测试1",
    "image_url": null
    },
    {
    "id": 16,
    "name": "1111",
    "category_id": 5,
    "type": 1,
    "score": 1,
    "image_id": 2,
    "category_name": "学生测试1",
    "image_url": "http://assess.uxuj.test/uploads/behavior/behavior02.png"
    }
    ]
    },
    {
    "id": 7,
    "name": "学生测试2",
    "list": [
    {
    "id": 12,
    "name": "测试1",
    "category_id": 7,
    "type": 1,
    "score": 2,
    "image_id": 0,
    "category_name": "学生测试2",
    "image_url": null
    }
    ]
    }
    ],
    "negative": [
    {
    "id": 5,
    "name": "学生测试1",
    "list": [
    {
    "id": 11,
    "name": "测试1",
    "category_id": 5,
    "type": 2,
    "score": 1,
    "image_id": 0,
    "category_name": "学生测试1",
    "image_url": null
    }
    ]
    }
    ]
    }
    })
     */
    public function behaviors()
    {
        $record_id = $this->request->request(('record_id'));
        $data = BehaviorCategory::getBehaviorData($this->behaviorCategoryType, $record_id, $this->auth->id, $this->auth->school_id);
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (评价)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/18)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/addBehaviorRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="record_id", type="int", required=false, description="记录id 修改的时候必填", sample="")
     * @ApiParams   (name="id", type="int", required=true, description="学生 id", sample="")
     * @ApiParams   (name="behavior_id", type="int", required=true, description="行为 id", sample="")
     * @ApiParams   (name="comment", type="string", required=false, description="文字说明", sample="")
     * @ApiParams   (name="images", type="string", required=false, description="图片 以英文 , 分割", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function addBehaviorRecord()
    {
        $record_id = $this->request->request('record_id');
        $id = $this->request->request('id');
        $behavior_id = $this->request->request('behavior_id');
        //$count = $this->request->request('count', 1);
        $count = 1;
        $comment = $this->request->request('comment', '');
        $images = $this->request->request('images', '');

        $behaviorRecord = [];
        if ($record_id) {
            $behaviorRecord = BehaviorRecord::where('record_user_id', $this->auth->id)->where('id', $record_id)->find();
            if (!$behaviorRecord) {
                $this->error('记录不存在');
            }
        }

        $behavior = \app\common\model\Behavior::alias('behavior')
            ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = behavior.category_id')
            ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id')
            ->where('behavior.id', $behavior_id)
            ->whereIn('category.type', $this->behaviorCategoryType)
            ->field('behavior.*,category.name category_name,category.type category_type,category.is_deduct,image.url image_url')
            ->find();

        if (!$behavior) {
            $this->error('行为不存在');
        }

        $ret['data'] = \app\common\model\Student::alias('student')
            ->join('__CLASSES__ classes', 'classes.id = student.class_id')
            ->join('__GRADE__ grade', 'grade.id = student.grade_id')
            ->join('__SCHOOL__ school', 'school.id = student.school_id')
            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->where('student.id', $id)
            ->field('student.*,school.name school_name,classes.name class_name,grade.name grade_name,classes.headmaster headmaster_id,user.nickname headmaster_name')
            ->find();

        if (!$ret['data']) {
            $this->error('学生不存在');
        }

        if ($ret['data'] && !strstr($ret['data']->avatar, 'http') && strstr($ret['data']->avatar, '/uploads/')) {
            $ret['data']->avatar = config('mp.url') . $ret['data']->avatar;
        }
        $ret['data']->gender_text = BaseUser::getGender($ret['data']->gender);

        $user = $this->auth->getUserinfo();

        Db::startTrans();
        try {

            if ($behaviorRecord) {
                db('behavior_record_detail')->where('record_id', $behaviorRecord->id)->delete();
                db('behavior_record_image')->where('record_id', $behaviorRecord->id)->delete();
            } else {
                $behaviorRecord = new BehaviorRecord();
                $behaviorRecord->save([
                    'record_user_id' => $user['id'],
                    'record_username' => $user['nickname'],
                    'record_user_group' => $user['group_name'],
                    'behavior_category_type' => BehaviorCategory::STUDENT,
                    'school_id' => $ret['data']['school_id'],
                    'class_id' => $ret['data']['class_id'],
                    'teacher_id' => $ret['data']['headmaster_id'],
                    'student_id' => $ret['data']['id'],
                    'comment' => $comment,
                    'json_data' => json_encode([
                        'school_id' => $ret['data']['school_id'],
                        'school_name' => $ret['data']['school_name'],
                        'grade_id' => $ret['data']['grade_id'],
                        'grade_name' => $ret['data']['grade_name'],
                        'class_id' => $ret['data']['class_id'],
                        'class_name' => $ret['data']['class_name'],
                        'headmaster_id' => $ret['data']['headmaster_id'],
                        'headmaster_name' => $ret['data']['headmaster_name'],
                        'student_id' => $ret['data']['id'],
                        'student_name' => $ret['data']['name'],
                        'student_number' => $ret['data']['number'],
                        'student_gender' => $ret['data']['gender_text'],
                    ])
                ]);
            }

            $behaviorRecordDetail = new BehaviorRecordDetail();
            $behaviorRecordDetail->save([
                'record_id' => $behaviorRecord->id,
                'behavior_category_id' => $behavior['category_id'],
                'behavior_category_type' => $behavior['category_type'],
                'behavior_id' => $behavior['id'],
                'behavior_name' => $behavior['name'],
                'behavior_type' => $behavior['type'],
                'behavior_image_id' => $behavior['image_id'],
                'behavior_image_url' => $behavior['image_url'],
                'unit_score' => $behavior['type'] == 1 ? $behavior['score'] : $behavior['score'] * (-1),
                'count' => $count,
                'score' => $behavior['type'] == 1 ? $count * $behavior['score'] : $count * $behavior['score'] * (-1),
                'is_deduct' => $behavior['is_deduct'],
                'student_id' => $ret['data']['id'],
                'class_id' => $ret['data']['class_id']
            ]);
            if ($images) {
                if (!is_array($images)) {
                    $images = explode(',', $images);
                    $behavior_record_image_data = [];
                    foreach ($images as $key => $image) {
                        $behavior_record_image_data[] = [
                            'record_id' => $behaviorRecord->id,
                            'record_detail_id' => $behaviorRecordDetail->id,
                            'url' => $image,
                        ];
                    }
                    $behaviorRecordImage = new BehaviorRecordImage();
                    $behaviorRecordImage->saveAll($behavior_record_image_data);
                }
            }

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * @ApiTitle    (评价记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/18)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/behaviorRecords)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="学生 id", sample="")
     * @ApiParams   (name="time_type", type="int|string", required=true, description="时间刷选类型 默认本月", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数", sample="")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|last week=上周 5|7 day=近7天 6|month=本月 7|last month=上月 8|30 day=近30天 9|quarter=本季度 10|last quarter=上季度 11|year=本年 12|last year=上年 13|1 month=近一个月 14|3 month=近三个月", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function behaviorRecords()
    {
        $id = $this->request->request('id');
        $page = $this->request->request('page', 1);
        $listRows = $this->request->request('listRows');
        $time_type = $this->request->request('time_type');

        if (1 == $page) {
            $charts = BehaviorRecord::getCharts(BehaviorCategory::STUDENT, $id);
            if (isset($charts['error'])) {
                $this->error($charts['msg']);
            }
        }

        $list = BehaviorRecord::getRecords(BehaviorCategory::STUDENT, $id, $this->behaviorCategoryType, $time_type, $listRows);

        if (isset($list['error'])) {
            $this->error($list['msg']);
        }

        $this->success('', compact('charts', 'list'));
    }
}
